using System;

using UnityEngine;
using UnityEngine.EventSystems;

/// <summary>
/// Sends a message to the remote object when something happens.
/// </summary>

[AddComponentMenu("UGUI/Interaction/Button Message (Legacy)")]
public class UGUIButtonMessage : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler, IPointerDownHandler, IPointerUpHandler, IPointerClickHandler, ISelectHandler, IDeselectHandler
{
    public enum Trigger
    {
        OnClick,
        OnMouseOver,
        OnMouseOut,
        OnPress,
        OnRelease,
        OnDoubleClick,
    }

    public GameObject target;
    public string functionName;
    public Trigger trigger = Trigger.OnClick;
    public bool includeChildren = false;

#pragma warning disable 0414
    bool mStarted = false;
#pragma warning restore 0414

    void Start() { mStarted = true; }

    void OnEnable() { }

    void OnHover(bool isOver)
    {
        if (enabled)
        {
            if (((isOver && trigger == Trigger.OnMouseOver) ||
                (!isOver && trigger == Trigger.OnMouseOut))) Send();
        }
    }

    void OnPress(bool isPressed)
    {
        if (enabled)
        {
            if (((isPressed && trigger == Trigger.OnPress) ||
                (!isPressed && trigger == Trigger.OnRelease))) Send();
        }
    }

    void OnSelect(bool isSelected)
    {
        if (enabled)
        {
            OnHover(isSelected);
        }
    }

    void OnClick() { if (enabled && trigger == Trigger.OnClick) Send(); }

    void OnDoubleClick() { if (enabled && trigger == Trigger.OnDoubleClick) Send(); }

    void Send()
    {
        if (string.IsNullOrEmpty(functionName)) return;
        if (target == null) target = gameObject;

        if (includeChildren)
        {
            Transform[] transforms = target.GetComponentsInChildren<Transform>();

            for (int i = 0, imax = transforms.Length; i < imax; ++i)
            {
                Transform t = transforms[i];
                t.gameObject.SendMessage(functionName, gameObject, SendMessageOptions.DontRequireReceiver);
            }
        }
        else
        {
            target.SendMessage(functionName, gameObject, SendMessageOptions.DontRequireReceiver);
        }
    }

    public void OnPointerEnter(PointerEventData eventData)
    {
        OnHover(true);
    }

    public void OnPointerExit(PointerEventData eventData)
    {
        OnHover(false);
    }

    public void OnPointerDown(PointerEventData eventData)
    {
        OnPress(true);
    }

    public void OnPointerUp(PointerEventData eventData)
    {
        OnPress(false);
    }

    public void OnPointerClick(PointerEventData eventData)
    {
        OnClick();
    }

    public void OnSelect(BaseEventData eventData)
    {
        OnSelect(true);
    }

    public void OnDeselect(BaseEventData eventData)
    {
        OnSelect(false);
    }
}
